package com.mall.shopping.services;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemCatMapper;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.sun.org.apache.bcel.internal.generic.LineNumberGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RBatch;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

@Service
@Slf4j
public class ICartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    MemberMapper memberMapper;




    /**
     * 添加商品到购物车
     * @param request
     * @return
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse response = new AddCartResponse();
        CartProductDto cartProductDto;
        String userCart = "cart_userId_" + request.getUserId();
        RMap<Long, CartProductDto> rCart = redissonClient.getMap(userCart);
        if (!rCart.isExists() || !rCart.containsKey(request.getProductId())) {
            Item item = itemMapper.selectByPrimaryKey(request.getProductId());
            if (item == null) {
                response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
                response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
                return response;
            }
            cartProductDto = CartItemConverter.item2Dto(item);
            cartProductDto.setProductNum(Long.valueOf(request.getProductNum()));
            cartProductDto.setChecked("true");
            rCart.put(request.getProductId(),cartProductDto);
        } else {
            cartProductDto = rCart.get(request.getProductId());
            long newNum = cartProductDto.getProductNum() + Long.valueOf(request.getProductNum());
            cartProductDto.setProductNum(newNum);
            rCart.put(request.getProductId(), cartProductDto);
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    @Override

    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
                 DeleteCartItemResponse response=new DeleteCartItemResponse();
                 String usercart="cart_userId_"+request.getUserId();
                 RMap<Long,CartProductDto> rMap=redissonClient.getMap(usercart);
                 try{
                         rMap.remove(request.getItemId());
                     response.setCode(ShoppingRetCode.SUCCESS.getCode());
                     response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                 }catch(Exception e){
                     response.setCode(ShoppingRetCode.SYSTEM_TIMEOUT.getCode());
                     response.setMsg(ShoppingRetCode.SYSTEM_TIMEOUT.getMessage());
                 }

                 return response;}

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        request.requestCheck();
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();
        RMap<Long, CartProductDto> map = redissonClient.getMap("cart_userId_" + request.getUserId());
        try {
            Collection<CartProductDto> cartProductDtos = map.readAllValues();
            Iterator<CartProductDto> iterator = cartProductDtos.iterator();
            while (iterator.hasNext()) {
                CartProductDto cartProductDto = iterator.next();
                if ("true".equals(cartProductDto.getChecked())) {
                    map.fastRemove(cartProductDto.getProductId());
                }
            }
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            e.printStackTrace();
            return response;
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }

    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        String userCart = "cart_userId_" + request.getUserId();
        RMap<Long, CartProductDto> rMap = redissonClient.getMap(userCart);
        try {
            CartProductDto cartProductDto = rMap.get(request.getItemId());
            cartProductDto.setChecked(request.getChecked());
            cartProductDto.setProductNum(new Long(request.getNum()));
            rMap.put(request.getItemId(),cartProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            response.setCode(ShoppingRetCode.SYSTEM_TIMEOUT.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_TIMEOUT.getMessage());
        }
        return response;

    }

    /**
     * 根据user_id获取购物车列表
     * @param request
     * @return
     */
    @Override
    public CartListByIdResponse getCartListByUsername(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        ObjectMapper objectMapper = new ObjectMapper();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUsername());
        List<Member> members = memberMapper.selectByExample(example);
        String key = "cart_userId_" + members.get(0).getId().toString();

        //使用hvlas 语句。获得结果集
        RMap<String, CartProductDto> map = redissonClient.getMap(key);
        Collection<CartProductDto> carts = map.readAllValues();
        ArrayList<CartProductDto> cartProductDtos = new ArrayList<>(carts);
        if (carts.size() == 0 || carts == null) {
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setCode(ShoppingRetCode.SUCCESS.getMessage());
            response.setCartProductDtos(cartProductDtos);
            return response;
        }
//        //根据结果集获得将string转换成CartProductDto对象
//        Iterator<CartProductDto> iterator = carts.iterator();
//        while (iterator.hasNext()) {
//            CartProductDto cartStr = iterator.next();
//
//            CartProductDto cartProductDto = null;
//            try {
//
//                //cartProductDto = objectMapper.readValue(cartStr, CartProductDto.class);
//            } catch (IOException e) {
//                response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
//                response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
//                e.printStackTrace();
//                return response;
//            }
//            cartProductDtos.add(cartProductDto);
//        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setCode(ShoppingRetCode.SUCCESS.getMessage());
        response.setCartProductDtos(cartProductDtos);
        return response;
    }

}
